/**
 * 商品详情
 */
$(function () {
    var user_id = $("#user").data("id"),
            active_tab = $("#user").data("tab"),
            addImageBtn = $("#addImageBtn"),
            upload_btn_default = '<i class="fa fa-check mr10"></i>保存图片',
            upload_btn_process = '<i class="fa fa-spin fa-spinner mr10"></i>上传中...',
            imageContainer = $("#image-container"),
            // 资金记录
            fundType = $("select[name=fundType]"),
            fundOperation = $("select[name=fundOperation]"),
            fundStatus = $("select[name=fundStatus]");

    /**
     * 设置当前显示的tab页
     */
    if (active_tab !== '') {
        $("#li-" + active_tab).addClass("active");
        $("#tab-" + active_tab).addClass("active");
    } else {
        $("#li-info").addClass("active");
        $("#tab-info").addClass("active");
    }

    /**
     * 刷新页面并跳转到相应tab
     */
    var url = location.href.split('?tab=')[0];
    var getUrl = {
        info: url + "?tab=info",
        images: url + "?tab=images",
        fund: url + "?tab=fund",
    };
    var refresh = function (tab) {
        location.href = getUrl[tab];
    };

    var zpad = function (n, l) {
        return rep(l - n.toString().length, '0') + n.toString();
    };


    /**
     * 初始化商品操作记录列表
     */
    var initFundRecordTable = function () {

        // 初始化列表
        var table = $('#fundRecordList').DataTable({
            "processing": true,
            "serverSide": true,
            "ajax": {
                "url": "pointsystem/getUserFundRecord",
                "data": function (d) {
                    d.userId = user_id;
                    d.fundType = fundType.val();
                    d.fundOperation = fundOperation.val();
                    d.fundStatus = fundStatus.val();
                },
                "type": "POST"
            },
            "aoColumnDefs": [{
                    "targets": 0, //操作人
                    "mRender": function (data, type, row) {
                        return row.record.userId;
                    }
                }, {
                    "targets": 1, //流水号
                    "visible": false,
                    "mRender": function (data, type, row) {
                        return row.record.transId === null ? '-' : row.record.transId;
                    }
                },
                {
                    "targets": 2, //资金类型
                    "mRender": function (data, type, row) {
                        return sysFundType[row.record.type];
                    }
                },
                {
                    "targets": 3, //操作时间
                    "searchable": false,
                    "mRender": function (data, type, row) {
                        return $.format.date(new Date(row.record.recordTime), "yyyy/MM/dd HH:mm");
                    }
                }, {
                    "targets": 4, //备注
                    "searchable": false,
                    "mRender": function (data, type, row) {
                        return row.record.description;
                    }
                }],
            "order": [4, 'desc'],
            "oLanguage": chinese,
            "language": {
                "decimal": ",",
                "thousands": ",",
            },
            "iDisplayLength": 20,
            "aLengthMenu": [
                [5, 10, 20, 50, 100, -1],
                [5, 10, 20, 50, 100, "全部"]
            ],
            "sDom": 't<"dt-panelfooter clearfix"lp>',
            "initComplete": function (settings, json) {
                $("#fundCount").text(json.recordsTotal);
            }
        });

        $('#searchFundRecord').on('click', function () {
            table.ajax.reload();
        });
    };


    /**
     *  初始化日历
     */
    var initDatePicker = function () {
        dateOfBirth_input.datepicker({
            prevText: '<i class="fa fa-chevron-left"></i>',
            nextText: '<i class="fa fa-chevron-right"></i>',
            showButtonPanel: false
        });
        // 设置默认日期
        dateOfBirth_input.datepicker('setDate', new Date());
    };

    /**
     * 初始化图片上传控件
     */
    var initUploader = function () {
        var doUploadBtn = $("#doUploadBtn"), document = null;
        /**
         * 弹出文件选择框
         */
        $('#upZone').click(function () {
            $('#fileInput').click();
        });
        $('#fileInput').on("change", function (e) {
            var files = e.target.files;
            if (!files.length || !window.FileReader) {
                return; // no file selected, or no FileReader support
            }
            document = files[0];
            $("#fileName").val(document.name);
            if (/^image/.test(document.type)) {
                var reader = new FileReader();
                var img = new Image();
                reader.readAsDataURL(document);
                reader.onload = function (e) {
                    img.src = e.target.result;
                    setTimeout(function () {
                        if (img.width === 800 && img.height === 800) {
                            $("#imagePreview").html($('<img class="h-150"/>').attr('src', e.target.result));
                        } else {
                            $("#doUploadBtn").css("display", "none");
                            alert("选择的图片必须是800*800!");
                            location.reload();
                        }
                    }, 1000);
                }
            }
        });
        /**
         * 保存图片：触发上传
         */
        doUploadBtn.on("click", function () {
            if (document === null) {
                alert("尚未选择图片");
            } else {
                $('form[name=uploadForm]').trigger('submit');
            }
        });
        /**
         *  上传文件
         */
        $('form[name=uploadForm]').on('submit', function (event) {
            event.stopPropagation();
            event.preventDefault();

            var url = 'pointsystem/upload';
            var formData = new FormData();
            formData.append("file", document);
            formData.append("name", $("#fileName").val());
            formData.append("desc", $("#description").val());
            formData.append("realm", 'USER');
            formData.append("cid", $("#commodityId").data("id"));
            formData.append("id", user_id);

            doUploadBtn.prop("disabled", true).html(upload_btn_process);
            $.ajax({
                url: url,
                data: formData,
                processData: false,
                contentType: false,
                type: 'POST',
                success: function (res) {
                    doUploadBtn.html(upload_btn_default).prop("disabled", false);
                    if (res.success) {
                        alert("图片上传成功！");
                        refresh("images");
                    } else {
                        alert(res.message);
                    }
                }
            }).fail(function () {
                alert('图片上传失败：服务器错误');
            });
        });
    };

    /**
     * 初始化事件
     */
    var initEvents = function () {

        /**
         * 添加图片
         */
        addImageBtn.on("click", function () {
            $.magnificPopup.open({
                removalDelay: 500, //delay removal by X to allow out-animation,
                alignTop: true,
                items: {
                    src: "#uploadPanel"
                },
                // overflowY: 'hidden', // 
                callbacks: {
                    beforeOpen: function (e) {
                        this.st.mainClass = 'mfp-slideDown';
                    }
                },
                midClick: true // allow opening popup on middle mouse click. Always set it to true if you don't provide alternative source.
            });
        });

        /**
         * 刪除图片
         */
        imageContainer.on("click", ".delete-link", function (e) {
            e.stopPropagation();
            e.preventDefault();
            if (confirm("确定要删除图片？")) {
                var id = $(this).data("id");
                $.get("store/deleteImageById/" + id, function (res) {
                    if (res === true) {
                        alert("图片删除成功");
                        refresh("images");
                    } else {
                        alert("图片删除失败");
                    }
                });
            }
        });
    };

    // 初始化图片预览弹出框
    var initPopUp = function () {
        $('.image img').magnificPopup({
            type: 'image',
            callbacks: {
                beforeOpen: function (e) {
                    // we add a class to body to indicate overlay is active
                    // We can use this to alter any elements such as form popups
                    // that need a higher z-index to properly display in overlays
                    $('body').addClass('mfp-bg-open');

                    // Set Magnific Animation
                    this.st.mainClass = 'mfp-zoomIn';

                    // Inform content container there is an animation
                    this.contentContainer.addClass('mfp-with-anim');
                },
                afterClose: function (e) {
                    $('body').removeClass('mfp-bg-open');
                },
                elementParse: function (item) {
                    // Function will fire for each target element
                    // "item.el" is a target DOM element (if present)
                    // "item.src" is a source that you may modify
                    item.src = item.el.data('url');
                }
            },
            removalDelay: 200 //delay removal by X to allow out-animation
        });
    };

    /**
     * 获取用户认证图片
     */
    var loadImages = function () {
        $.post("store/listImageByOwner", {
            ownerId: user_id,
            realm: 'USER'
        }, function (data) {
            if (data && data.totalSize > 0) {
                for (var i = 0; i < data.totalSize; i++) {
                    var img = data.result[i];
                    img.createTime = function () {
                        return $.format.date(new Date(this.recordTime), "yyyy/MM/dd");
                    };
                    img.vclass = function () {
                        return this.visible ? 'text-system' : '';
                    };
                    var rendered = sys.render("#imageTemplate", img);
                    imageContainer.prepend($(rendered));
                }
                initPopUp();
            } else {
                $("#loading").html("尚未添加认证图片");
            }
        });
    };

    var loadUserData = function () {
        $.get("user/getDataById/" + user_id, function (data) {
            if (data) {
                initPnrAccountStatus(data.account);
                initUserFund(data.fund);
                initUserInfo(data);
                // 获取汇付账号信息
                initPaymentData();

                $("#loanCount").html(data.loanCount);
                $("#loanAmount").html($.number(data.loanAmount, 2));
                $("#investCount").html(data.investCount);
                $("#investAmount").html($.number(data.investAmount, 2));

                if (data.referee) {
                    $("#referee").html(sys.render("#refereeTemplate", data.referee));
                } else {
                    $("#referee").html('未指定');
                }
            }
        });
    };

    var initPnrAccountStatus = function (account) {
        var pnrAccount = $("#pnrAccount");
        if (account !== null) {
            pnrAccount.html('<span class="label label-xs label-system">已开通</span>');
            $("#pnrAccount").data("hasaccount", true);
        } else {
            pnrAccount.html('<span class="label bg-light darker label-xs">尚未开通</span>');
            $("#pnrAccount").data("hasaccount", false);
        }
    };

    var status = $("#content").data("status"),
            dateRangePicker = $('#daterangepicker');

    $(".repayment_" + status).addClass("active");
    var dateRangePicker = $('#daterangepicker');
    var initDateRangePicker = function () {
        var rangePast = {
            '今天': [moment(), moment()],
            '昨天': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
            '最近7天': [moment().subtract(6, 'days'), moment()],
            '最近30天': [moment().subtract(29, 'days'), moment()],
            '本月': [moment().startOf('month'), moment().endOf('month')],
            '上个月': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
        };
        var rangeFuture = {
            '今天': [moment(), moment()],
            '未来7天': [moment(), moment().add(6, 'days')],
            '未来30天': [moment(), moment().add(29, 'days')],
            '未来60天': [moment(), moment().add(59, 'days')],
            '本月': [moment().startOf('month'), moment().endOf('month')],
            '下个月': [moment().add(1, 'month').startOf('month'), moment().add(1, 'month').endOf('month')]
        };

        dateRangePicker.daterangepicker({
            ranges: rangePast,
            startDate: moment().subtract(29, 'days'),
            endDate: moment(),
            applyClass: "btn-primary btn-block",
            cancelClass: "btn-block",
            format: "YYYY-MM-DD",
            locale: {
                applyLabel: '确定',
                clearLabel: "取消",
                fromLabel: '开始时间',
                toLabel: '结束时间',
                weekLabel: '周',
                customRangeLabel: '选择范围',
                daysOfWeek: "日_一_二_三_四_五_六".split("_"),
                monthNames: "一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月".split("_"),
                firstDay: 0
            },
            opens: "left"
        });

        var formatDate = function (date) {
            return $.format.date(new Date(date), "yyyy/MM/dd");
        };
        // 根据状态设定初始日期
        var defaultDate = formatDate(moment().subtract(29, 'days')) + ' - ' + formatDate(moment());
        dateRangePicker.val(defaultDate);
        $(".daterangepicker .ranges ul li:last").hide();
        $(".daterangepicker .ranges .daterangepicker_start_input").remove();
        $(".daterangepicker .ranges .daterangepicker_end_input").remove();
        $(".daterangepicker .ranges .cancelBtn").remove();
    };

    var initPage = function () {
        loadUserData();
        initDateRangePicker();
        initEvents();
        loadImages();
        initUploader();
        initFundRecordTable();
    };
    // 初始化页面
    initPage();
});